var router = require('koa-router')();
var config = require('../config').wechat;
var sha1 = require('sha1');
var request = require('request');
var utils = require('../libs/util');
var Wechat = require('../libs/wechat');
var autoReplay = require('../libs/robot');

/***
 * -------------------------------- 微信授权 --------------------------------
 */

/***
 *  2. 消息自动回复
 */
router.post('/', async (ctx, next) => {
  // 1. 获取请求体内容
  let xmlContent = await recieveData(ctx);
  // 2. xml格式数据转换成json
  const data = await utils.xmlToJson(xmlContent);
  // 3. 消息内容格式化
  const message = await utils.formatMessage(data.xml);
  const { Content, CreateTime, FromUserName, MsgId, MsgType, ToUserName } = message;
  // 开始准备回复
  let wechat = new Wechat(config);

  // 获取自动回复机器人内容
  console.log("%c ------- 消息内容--------- ", 'color:red', Content);
  const msg = await autoReplay(Content)
  // 4. 自定义回复内容
  const response = {
    toUserName: FromUserName,
    fromUserName: ToUserName,
    createTime: CreateTime,
    msgType: 'text',
    content: msg
  }
  await ctx.render('weixin', response);
});

/***
 * -------------------------------- 网页访问 --------------------------------
 */
router.get('/movie', async (ctx, next) => {
  // 1. 获取access_token
  let wechat = new Wechat(config);
  var data = await wechat.fetchAccessToken();
  var access_token = data.access_token;
  // 2. 通过access_token 换取网页授权的access_token 此处命名为ticket
  var ticketData = await wechat.fetchTicket(access_token);
  var ticket = ticketData.ticket;
  // 3. 将ticket,url等信息进行签名算法
  const params = utils.sign(ticket, ctx.request.href);
  // 3. 将参数 传入网页，进行网页授权
  await ctx.render('movie', params);
});

router.get('/article', async (ctx, next) => {
  // 1. 获取access_token
  let wechat = new Wechat(config);
  var data = await wechat.fetchAccessToken();
  var access_token = data.access_token;
  // 2. 通过access_token 换取网页授权的access_token 此处命名为ticket
  var ticketData = await wechat.fetchTicket(access_token);
  var ticket = ticketData.ticket;
  // 3. 将ticket,url等信息进行签名算法
  const params = utils.sign(ticket, ctx.request.href);
  // 获取用户信息
  // const webData = await wechat.getWebToken(ctx);
  // const userInfo = await wechat.userInfo(webData);
  // 3. 将参数 传入网页，进行网页授权
  // 1. 判断是否已经进行了授权
  if (!ctx.session.auth || !ctx.session.auth.appId || ctx.session.auth.errcode) {
    let wechat = new Wechat(config);
    const redirectUrl = ctx.origin + '/redirect';
    wechat.doAuth.call(ctx, redirectUrl);
    return;
  }
  const user = ctx.session.user;
  await ctx.render('article', { ...params, user });
});
/**
 * 获取之后跳转到redirect路径
 */
router.get('/userCenter', async (ctx, next) => {
  // 1. 判断是否已经进行了授权
  if (!ctx.session.auth || !ctx.session.auth.appId || ctx.session.auth.errcode) {
    let wechat = new Wechat(config);
    const redirectUrl = ctx.origin + '/redirect';
    wechat.doAuth.call(ctx, redirectUrl);
    return;
  }
  const user = ctx.session.user;
  await ctx.render('user', user);

});
// 调用支付接口
router.get('/pay', async (ctx, next) => {
  // 1. 获取access_token
  let wechat = new Wechat(config);
  var data = await wechat.fetchAccessToken();
  var access_token = data.access_token;
  // 2. 通过access_token 换取网页授权的access_token 此处命名为ticket
  var ticketData = await wechat.fetchTicket(access_token);
  var ticket = ticketData.ticket;
  // 3. 将ticket,url等信息进行签名算法
  const params = utils.sign(ticket, ctx.request.href);
  // 3. 将参数 传入网页，进行网页授权
  await ctx.render('payment', params);

});

// 微信重定向跳转
router.get('/redirect', async (ctx, next) => {
  let wechat = new Wechat(config);
  // 2. 通过code换取access_token
  const data = await wechat.getWebToken(ctx);
  // 3. 通过access_token获取用户信息
  const userInfo = await wechat.userInfo(data);
  ctx.session.user = userInfo;
  if (ctx.session.redirect) {
    ctx.redirect(ctx.session.redirect);
  } else {
    ctx.body = "获取用户信息成功，正在准备重定向跳转"
  }
});


/**
 *  --------------------------------  方法区 --------------------------------
 */
let recieveData = function (_this) {
  return new Promise(function (resolve, reject) {
    let buf = ''
    _this.req.setEncoding('utf8')
    _this.req.on('data', (chunk) => {
      buf += chunk
    })
    _this.req.on('end', () => {
      utils.xmlToJson(buf)
        .then(resolve(buf))
        .catch(reject)
    })
  })
}


module.exports = router;
